package annotate.utils;



import annotate.en.Cache;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheUtils {
    private static Map<String,Object> cacheMap = new ConcurrentHashMap<>();
    private static final String CACHE_SEPARATE = "::";
    public static Object invokeMethod(Object obj,String methodName,Object... params){

       Class<?> objClass = obj.getClass();

        Object result = null;
       try {
           if (params == null || params.length == 0){
               //无差数，以大key为缓存的key
               Method method = objClass.getDeclaredMethod(methodName);
               method.setAccessible(true);
               Cache cache = method.getAnnotation(Cache.class);
               //方法有Cache注解才进行缓存
               if (cache != null){
                   //获取key
                   String key = cache.key();
                   Object value = cacheMap.get(key);
                   if (value != null){
                       return value;
                   }

               }
                result = method.invoke(obj);
               if (cache!=null){
                   String key = cache.key();
                   cacheMap.put(key,result);

               }

           }else {
               int size = params.length;
               Class<?>[] classes = new Class[size];
               Object[] paramValues = new Object[size];
               for (int i = 0; i < params.length; i++){
                   classes[i] = params[i].getClass();
                   paramValues[i] = params[i];
               }
               Method method = objClass.getDeclaredMethod(methodName,classes);
               method.setAccessible(true);

               Cache cache1 = method.getAnnotation(Cache.class);
               Cache cache = method.getAnnotation(Cache.class);
               //判断是否有cache注解
               if (cache != null){
                   String key = cache.key();
                   Object valueKey = paramValues[0];
                   //拼接缓存key
                   String CacheKey = key + CACHE_SEPARATE + valueKey;
                   //从缓存中查询数据
                   Object value = cacheMap.get(CacheKey);
                   if (value != null){
                       return value;
                   }
               }
               result = method.invoke(obj,paramValues);
               //判断是否有cache注解
               if (cache != null){
                   String key = cache.key();
                   Object valueKey = paramValues[0];
                   //拼接缓存key
                   String CacheKey = key + CACHE_SEPARATE + valueKey;
                   //将数据放入缓存
                   cacheMap.put(CacheKey,result);

               }
           }

       }catch (Exception e){
           e.printStackTrace();
       }

        return result;
    }

}
